package controller.login;

import java.io.PrintWriter;
import java.util.Enumeration;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.json.simple.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import entity.user.User;
import log.annotation.ControllerAnnotation;
import service.user.IUserService;
import util.MYUtil;

@Controller
@RequestMapping("/login")
public class LoginController {
	@Resource
	private IUserService userServiceImpl;

	public LoginController() {
		System.out.println("-------LoginController------");
	}

	/**
	 * 登录
	 * 
	 * @param out
	 * @param request
	 * @param name
	 * @param pwd
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/loginIn")
	@ControllerAnnotation(app = "蚂蚁", classname = "controller.login.LoginController", function = "系统管理", methodname = "loginIn", model = "系统管理", opercation = "登录", isMenu = false, menuName = "")
	public void loginIn(PrintWriter out, HttpServletRequest request, String account, String pwd) {
		JSONObject data = new JSONObject();
		try {
			User user = userServiceImpl.login(account, MYUtil.Md5Str(pwd));
			if (user != null) {
				data.put("flag", true);
				request.getSession().setAttribute(request.getSession().getId(), user.getId());
				request.getSession().setAttribute("user", user);
			} else {
				data.put("flag", false);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		out.write(data.toJSONString());
	}

	/**
	 * 退出
	 * 
	 * @param out
	 * @param request
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/loginOut")
	@ControllerAnnotation(app = "蚂蚁", classname = "controller.login.LoginController", function = "系统管理", methodname = "loginOut", model = "系统管理", opercation = "退出", isMenu = false, menuName = "")
	public void loginOut(PrintWriter out, HttpServletRequest request) {
		// 清除和当前用户有关的所有session数据
		Enumeration<String> em = request.getSession().getAttributeNames();
		while (em.hasMoreElements()) {
			request.getSession().removeAttribute(em.nextElement().toString());
		}
		request.getSession().invalidate();
		JSONObject data = new JSONObject();
		data.put("flag", true);
		out.write(data.toJSONString());
	}

}
